package com.yzt.zhuju.network;

import android.text.TextUtils;

import com.alibaba.fastjson.JSONObject;
import com.yzt.zhuju.RXingUtils;
import com.yzt.zhuju.config.AppConfig;
import com.yzt.zhuju.network.config.ApiConstant;
import com.yzt.zhuju.utils.DeviceUtils;
import com.yzt.p_base.utils.AppInfoUtils;
import com.yzt.p_base.utils.Base64Utils;
import com.yzt.p_base.utils.MD5Util;
import com.yzt.p_base.utils.TLogManager;

import java.io.IOException;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;

/**
 * author : bob
 * date   : 2022/11/30
 * desc   : 请求拦截器
 */
public class HeadInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {

        Request request = chain.request();
        Request.Builder requestBuilder = request.newBuilder();

        try {
            String token = RXingUtils.getLoginToken();

            String sign = "";
            HttpUrl httpUrl = request.url();
            if ("GET".equals(request.method())) {

                String query = httpUrl.encodedQuery();
                if (!TextUtils.isEmpty(query)) {
                    //get请求处理url
                    sign = MD5Util.md5(token + httpUrl.encodedQuery());
                }
            } else {
                //post请求处理body
                RequestBody requestBody = request.body();
                if (requestBody != null) {
                    MediaType contentType = requestBody.contentType();
                    boolean hasRequestBody = contentType != null && "json".equals(contentType.subtype());

                    if (hasRequestBody) {
                        Buffer buffer = new Buffer();
                        requestBody.writeTo(buffer);
                        String bodyJson = buffer.readByteString().utf8();
                        sign = MD5Util.md5(token + bodyJson);
                    }
                }
            }

            requestBuilder.addHeader("token", token);
            requestBuilder.addHeader("oaid", "");
            requestBuilder.addHeader("deviceId", DeviceUtils.getDeviceUuid(AppConfig.application).replace("-", ""));
            //1:ios 2:android
            requestBuilder.addHeader("client", "android");
            requestBuilder.addHeader("deviceBrand", DeviceUtils.getDeviceBrand());
            requestBuilder.addHeader("deviceName", DeviceUtils.getSystemModel());
            requestBuilder.addHeader("apiVersion", ApiConstant.SERVICE_API_VERSION);
            requestBuilder.addHeader("appOsVersion", DeviceUtils.getSysVersion());
            requestBuilder.addHeader("appVersionCode", AppInfoUtils.getAppVersionCode(AppConfig.context) + "");
            requestBuilder.addHeader("appVersionName", AppInfoUtils.getAppVersionName(AppConfig.context));
            requestBuilder.addHeader("appPackage", AppInfoUtils.getAppPackageName());

            if (!TextUtils.isEmpty(sign)) {
                requestBuilder.addHeader("s", sign);
            }

            Response response = chain.proceed(requestBuilder.build());

            String responseSign = response.header("s");

            ResponseBody responseBody = response.body();
            if (responseBody != null && !TextUtils.isEmpty(responseSign)) {
                String responseJson = responseBody.byteString().utf8();

                JSONObject jsonObject = JSONObject.parseObject(responseJson);

                if (jsonObject.get("data") != null) {
                    String data = jsonObject.get("data").toString();
                    String formatData = new String(Base64Utils.decode(data));
                    responseJson = responseJson.replace("\"" + data + "\"", formatData);
                }

                response = response.newBuilder().body(ResponseBody.create(responseJson, responseBody.contentType())).build();
            }
            return response;
        } catch (Exception e) {
            TLogManager.loge("network", "HeadIntercepter", "请求header添加异常:" + e.getMessage());
        }
        return chain.proceed(requestBuilder.build());
    }
}